using System.Collections.Generic;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;
using Mod.DisplayTypes.Models;
using System.Web.Script.Serialization;
using System.Linq;


namespace Mod.DisplayTypes.Settings
{
    /// <summary>
    /// Content type settings for SubMenu part
    /// </summary>
    public class DisplayTypePartTypePartSettings
    {
        private IList<RouteDefo> routeList;

        public DisplayTypePartTypePartSettings() 
        {
            AliasesGenerates = "[]";
        }

        public string AliasesGenerates { get; set; }

        public IList<RouteDefo> RouteList {
            get
            {
                if (routeList == null)
                    routeList = new JavaScriptSerializer().Deserialize<RouteDefo[]>(AliasesGenerates).ToList();

                return routeList;
            }
            set
            {
                routeList = value;
            }
        } 
    }

    public class RouteDefo
    {
        public string DisplayType { get; set; }
        public string Slugs { get; set; }
    }

    /// <summary>
    /// Overrides default editors to enable putting settings on SubMenu part.
    /// </summary>
    public class DisplayTypePartSettingsHooks : ContentDefinitionEditorEventsBase
    {

        /// <summary>
        /// Overrides editor shown when part is attached to content type. Enables adding setting field to the content part
        /// attached.
        /// </summary>
        /// <param name="definition"></param>
        /// <returns></returns>
        public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition)
        {
            if (definition.PartDefinition.Name != "DisplayTypePart")
                yield break;
            var model = definition.Settings.GetModel<DisplayTypePartTypePartSettings>();

            //model.RouteList.Add(new RouteDefo()
            //{
            //    DisplayType = "Detail",
            //    Slugs = "/hey/hey"
            //});

            yield return DefinitionTemplate(model);
        }

        public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel)
        {
            if (builder.Name != "DisplayTypePart")
                yield break;

            var model = new DisplayTypePartTypePartSettings();

            updateModel.TryUpdateModel(model, "DisplayTypePartTypePartSettings", null, null);

            builder.WithSetting("DisplayTypePartTypePartSettings.AliasesGenerates", model.AliasesGenerates);

            yield return DefinitionTemplate(model);
        }

    }
}